package com.sky.controller.user;

import com.sky.context.BaseContext;
import com.sky.entity.AddressBook;
import com.sky.result.Result;
import com.sky.service.AddressBookService;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/user/addressBook")
public class AddressBookController {

    @Autowired
    private AddressBookService addressBookService;

    @GetMapping("/list")
    @ApiOperation("查询当前用户全部地址信息")
    public Result<List<AddressBook>> list() {
        Long userId = BaseContext.getCurrentId();
        List<AddressBook> addressBookList = addressBookService.list(userId);
        return Result.success(addressBookList);
    }

    @PostMapping("")
    @ApiOperation("新增地址")
    public Result create(@RequestBody AddressBook addressBook) {
        addressBookService.create(addressBook);
        return Result.success();
    }

    @GetMapping("/{id}")
    @ApiOperation("根据 id 查询地址")
    public Result<AddressBook> getById(@PathVariable Long id) {
        AddressBook addressBook = addressBookService.getById(id);
        return Result.success(addressBook);
    }

    @PutMapping("")
    @ApiOperation("根据 id 修改地址")
    public Result updateById(@RequestBody AddressBook addressBook) {
        addressBookService.updateById(addressBook);
        return Result.success();
    }

    @DeleteMapping("")
    @ApiOperation("根据 id 删除地址")
    public Result deleteById(Long id) {
        addressBookService.removeById(id);
        return Result.success();
    }

    @PutMapping("/default")
    @ApiOperation("设置默认地址")
    public Result setDefaultAddress(@RequestBody AddressBook addressBook) {
        addressBookService.setDefaultAddress(addressBook);
        return Result.success();
    }

    @GetMapping("default")
    @ApiOperation("查询默认地址")
    public Result<AddressBook> getDefaultAddress() {
        AddressBook addressBook = addressBookService.getDefaultAddress();
        if (addressBook != null) {
            return Result.success(addressBook);
        } else {
            return Result.error("未查询到默认地址");
        }
    }
}
